<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <MOBan
        :list="goodList"
        @notiFather="notiFather"
        @changeCountfn="changeCountfn"
      ></MOBan>
      <tfoot>
        <tr>
          <td>合计:{{ totalPrice }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import MOBan from "./components/moban.vue";
export default {
  components: {
    MOBan,
  },
  data() {
    return {
      goodList: [
        {
          id: 1,
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          id: 2,
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          id: 3,
          name: "妲己",
          price: 2000,
          num: 1,
          checked: true,
        },
        {
          id: 4,
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    notiFather(checked, id) {
      this.goodList.forEach((item) => {
        if (item.id == id) {
          return (item.checked = checked);
        }
      });
    },
    changeCountfn(num, id) {
      this.goodList.forEach((item) => {
        if (item.id == id) {
          // item.num += num;
          item.num=item.num+num
        }
      });
    },
  },
  computed: {
    isAll: {
      get() {
        return this.goodList.every((ele) => ele.checked);
      },
      set(val) {
        this.goodList.forEach((ele) => (ele.checked = val));
      },
    },
    totalPrice() {
      return this.goodList
        .filter((item) => {
          return item.checked;
        })
        .reduce((a, b) => {
          return a + b.price * b.num;
        }, 0)
        .toFixed(2);
    },
  },
};
</script>

<style></style>
